# ==============================================================================
# DESCRIPTION ----
# ==============================================================================
# Master script to run all analysis scripts that do not utilize
# Nikkei NEEDS data (in order). 

# ==============================================================================
# HELPER FUNCTIONS ----
# ==============================================================================

# Helper function to safely source scripts
run_script <- function(script_name) {
  current_script <- script_name
  
  # Clear global environment but keep run_script() and scripts list
  rm(
    list = setdiff(ls(envir = .GlobalEnv), c("run_script", "scripts")),
    envir = .GlobalEnv
  )
  cat("\014")
  
  message("Running: ", current_script)
  tryCatch({
    source(current_script, echo = TRUE, max.deparse.length = Inf)
    message("Completed: ", current_script, "\n")
  }, error = function(e) {
    message("Error in ", current_script, ": ", e$message, "\n")
  })
}

# ==============================================================================
# SCRIPT LIST ----
# ==============================================================================
scripts <- c(
  "code/1.2_descriptive_figures.R",
  "code/4.1_event_study.R",
  "code/4.2_event_study_robustness.R", # Note: appendix figures only
  "code/5.1_npo_analysis_month.R",
  "code/5.2_npo_analysis_year.R" # Note: appendix figures only
)

# ==============================================================================
# RUN ALL SCRIPTS ----
# ==============================================================================
for (s in scripts) {
  run_script(s)
}
message("All scripts finished running.")
